<?php
if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../../').'/');
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'syntax.php');

class syntax_plugin_bbcodeextensions_classspan extends DokuWiki_Syntax_Plugin {

    function getType() { return 'formatting'; }
    function getPType() { return 'normal'; }
    function getAllowedTypes() { return array('formatting', 'substition', 'protected'); }   
    function getSort() { return 165; }
    function connectTo($mode) { 
        $this->Lexer->addEntryPattern('\[cs\=.*?\](?=.*?\x5B/cs\x5D)',$mode,'plugin_bbcodeextensions_classspan'); 
    }
    function postConnect() { $this->Lexer->addExitPattern('\[/cs\]','plugin_bbcodeextensions_classspan'); }

    function handle($match, $state, $pos, Doku_Handler $handler) {        
        switch ($state) {
          case DOKU_LEXER_ENTER :
            $omatch= $match;
            $match = explode('"',substr($match, 3, -1));
            return array($state, $match[1], $omatch);
          case DOKU_LEXER_UNMATCHED :
            return array($state, $match);
          case DOKU_LEXER_EXIT :
            return array($state, '');
        }
        return array();
    }

    /**
     * Create output
     */
    function render($mode, Doku_Renderer $renderer, $data) {
		if(in_array($mode, ['xhtml', 's5'], true)) {
			list($state, $match) = $data;
			$defcl= $this->getConf('class_preffix') ?? 'bbcodeextensions';

            switch ($state) {
              case DOKU_LEXER_ENTER :
                $renderer->doc .= <<<EOF
<span class="{$defcl} {$match}" >
EOF;
                break;

              case DOKU_LEXER_UNMATCHED :
                $match = $renderer->_xmlEntities($match);
                $renderer->doc .= $match;
                break;

              case DOKU_LEXER_EXIT :
                $renderer->doc .= '</span><!-- bbcodeextensions_span -->';
                break;

            } // switch
            return true;
        }
		if(in_array($mode, ['text'], true)) {
			list($state, $match) = $data;
			switch ($state) {
				case DOKU_LEXER_ENTER :
				break;
			
				case DOKU_LEXER_UNMATCHED :
				$renderer->doc .= $match;
				break;

				case DOKU_LEXER_EXIT :
				break;
			}
			return true;
		}
        return false;
    }


}
